<template>
  <div class="errorLianluWarp">
    <a-row :gutter="24" style="margin-bottom: 16px">
      <a-col :span="12">
        <a-button type="primary" @click="addErrorLianlu">新增</a-button>
      </a-col>
      <a-col :span="6" style="text-align: right">
        <a-button type="dashed" href="/api/errorLianlu/installModule">
          <DownloadOutlined />模板下载
        </a-button>
      </a-col>
      <a-col :span="2" style="text-align: right">
        <UploadFile @queryErrorLianluList="queryErrorLianluList" />
      </a-col>
      <a-col :span="2" style="text-align: right">
        <a-button @click="exportExcel">
          <FileExcelOutlined />导出
        </a-button>
      </a-col>
      <a-col :span="2" style="text-align: right">
        <a style="font-size: 12px" @click="expand = !expand;">
          <template v-if="expand">
            <UpOutlined />
          </template>
          <template v-else>
            <DownOutlined />
          </template>
          {{expand?'隐藏查询条件':'展示查询条件'}}
        </a>
      </a-col>
    </a-row>
    <a-row :gutter="24" v-show="expand">
      <a-col :span="18">
        <a-form ref="queryRef" :model="queryData">
          <a-form-item name="range-picker" label="查询时间区间">
            <a-range-picker
              v-model:value="queryData['error_time']"
              value-format="YYYY-MM-DD"
              :allowClear="false"
            />
          </a-form-item>
        </a-form>
      </a-col>
      <a-col :span="6" style="text-align: right">
        <a-button @click="resetForm" style="margin-right: 20px; margin-left: 20px">重置</a-button>
        <a-button type="primary" @click="queryErrorLianluList">查询</a-button>
      </a-col>
    </a-row>
    <a-table
      :columns="columns"
      :data-source="errorLianluList"
      bordered
      :pagination="false"
      :autoDataLoad="false"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record  }">
        <template
          v-if="column.dataIndex === 'error_time_start'"
        >{{formatTime(record.error_time_start, 'yyyy/MM/dd hh:mm')}}</template>
        <template
          v-if="column.dataIndex === 'error_time_end'"
        >{{record.error_time_end?formatTime(record.error_time_end, 'yyyy/MM/dd hh:mm'):''}}</template>
        <template
          v-if="column.dataIndex === 'record_date'"
        >{{formatTime(record.record_date, 'yyyy/MM/dd')}}</template>
        <template v-if="column.dataIndex === 'operation'">
          <a href="#" @click="editLianlu(record)" style="margin-right: 20px">编辑</a>
          <a-popconfirm
            title="确定要删除这一条链路吗?"
            ok-text="是"
            cancel-text="否"
            @confirm="delLianlu(record.id)"
          >
            <a href="#" style="color: red">删除</a>
          </a-popconfirm>
        </template>
      </template>
      <template #title>省局总局链路监控汇总</template>
      <template #footer>总局省局异常链路信息统计表</template>
    </a-table>
    <a-row :gutter="24" style="margin-top: 20px">
      <a-col :span="23" style="text-align: right">
        <a-pagination
          v-model:current="queryData.pageNumber"
          v-model:pageSize="queryData.pageSize"
          show-size-changer
          @change="queryErrorLianluList"
          :total="total"
          :showTotal="()=>`一共${total}条数据`"
        />
      </a-col>
    </a-row>
    <AddEditErrorLianlu
      :isShow="drawerData.isShow"
      :isAdd="drawerData.isAdd"
      :editErrorLianluData="editErrorLianluData"
      :errorLianluId="errorLianluId"
      @closeDrawer="closeDrawer"
      @queryErrorLianluList="queryErrorLianluList"
    />
  </div>
</template>
<script lang="ts">
import { Buffer } from 'buffer';
import { defineComponent, onMounted, reactive, Ref, ref } from 'vue';
import { DownOutlined, UpOutlined, DownloadOutlined, FileExcelOutlined } from '@ant-design/icons-vue';
import { getErrorLianluListApi, exportExcelErrorLianluApi, delErrorLianluListApi } from '../../utils/errorLianlu';
import { FormInstance, message } from 'ant-design-vue';
import AddEditErrorLianlu from '@/views/errorLianlu/components/AddEditErrorLianlu.vue';
import UploadFile from '@/views/errorLianlu/components/UploadFile.vue'
interface ErrorLianluDto {
  id?: string;
  lianlu_code: string;
  lianlu_name: string;
  lianlu_start: string;
  lianlu_end: string;
  error_time_start: string;
  error_time_end: string;
  error_reason: string;
  plan_error: string;
  record_date: string;
}
interface ResultDto {
  code: number
  data: Array<ErrorLianluDto>
  message: string
  total: number
}
interface QueryState {
  pageSize: number;
  pageNumber: number;
  error_time: [string, string];
}
let columns = [
  {
    title: '链路编号',
    dataIndex: 'lianlu_code',
  },
  {
    title: '链路名称',
    dataIndex: 'lianlu_name',
  },
  {
    title: '源端数据库',
    dataIndex: 'lianlu_start',
    width: 110
  },
  {
    title: '目标端数据库',
    dataIndex: 'lianlu_end',
    width: 110
  },
  {
    title: '问题发现时间',
    dataIndex: 'error_time_start',
  },
  {
    title: '问题解决时间',
    dataIndex: 'error_time_end',
  },
  {
    title: '问题简要原因',
    dataIndex: 'error_reason',
    width: 320
  },
  {
    title: '计划内升级或故障',
    dataIndex: 'plan_error',
    width: 150
  },
  {
    title: '时间',
    dataIndex: 'record_date',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 110
  }
];
export default defineComponent({
  components: { UpOutlined, DownOutlined, DownloadOutlined, FileExcelOutlined, AddEditErrorLianlu, UploadFile },
  setup() {
    // 查询信息的ref
    const queryRef = ref<FormInstance>();
    // 错误信息id用于编辑的时候传递
    let errorLianluId = ref<string>('');
    // 异常链路列表
    let errorLianluList: ErrorLianluDto[] = reactive([]);
    // 表格加载
    let tableLoading: Ref<boolean> = ref(false);
    // 是否展示查询条件
    let expand: Ref<boolean> = ref(false);
    // 异常链路信息总条数
    let total: Ref<number> = ref(0)
    // 查询条件数据
    let queryData = reactive({
      pageSize: 10,
      pageNumber: 1,
      error_time: ['', '']
    } as QueryState);
    // 子组件新增/编辑链路信息
    let editErrorLianluData = reactive({
      lianlu_code: '',
      lianlu_name: '',
      lianlu_start: '',
      lianlu_end: '',
      error_time_start: '',
      error_time_end: '',
      error_reason: '',
      plan_error: '异常',
      record_date: ''
    } as ErrorLianluDto)
    // 抽屉相关的数据
    let drawerData = reactive({
      isAdd: true,
      isShow: true
    })
    // 点击新增按钮
    const addErrorLianlu = function () {
      drawerData.isAdd = true;
      drawerData.isShow = true;
    }
    // 查询链路
    const queryErrorLianluList = function () {
      tableLoading.value = true;
      getErrorLianluListApi({
        pageSize: queryData.pageSize,
        pageNumber: queryData.pageNumber,
        recordDateStart: queryData.error_time[0],
        recordDateEnd: queryData.error_time[1]
      }).then(res => {
        const result = res as unknown as ResultDto;
        if (result.code === 200) {
          errorLianluList.length = 0;
          errorLianluList.push(...result.data);
          total.value = result.total;
        } else {
          message.error(result.message)
        }
        tableLoading.value = false;
      })
    }
    // 点击编辑按钮
    const editLianlu = function (record: ErrorLianluDto) {
      errorLianluId.value = record.id as string;
      Object.assign(editErrorLianluData, {
        lianlu_code: record.lianlu_code,
        lianlu_name: record.lianlu_name,
        lianlu_start: record.lianlu_start,
        lianlu_end: record.lianlu_end,
        error_time_start: formatTime(record.error_time_start, 'yyyy/MM/dd hh:mm', '-'),
        error_time_end: record.error_time_end ? formatTime(record.error_time_end, 'yyyy/MM/dd hh:mm', '-') : '',
        error_reason: record.error_reason,
        plan_error: record.plan_error,
        record_date: record.record_date
      })
      drawerData.isAdd = false;
      drawerData.isShow = true;
    }
    // 删除链路
    const delLianlu = function (id: string) {
      delErrorLianluListApi(id).then(res => {
        const result = res as unknown as ResultDto;
        if (result.code === 200) {
          message.success(result.message);
          queryErrorLianluList();
        }
      })
    }
    // 关闭抽屉
    const closeDrawer = function () {
      drawerData.isShow = false;
      Object.assign(editErrorLianluData, {
        lianlu_code: '',
        lianlu_name: '',
        lianlu_start: '',
        lianlu_end: '',
        error_time_start: '',
        error_time_end: '',
        error_reason: '',
        plan_error: '异常',
        record_date: ''
      })
      errorLianluId.value = '';
    }
    // 导出excel表格
    const exportExcel = function () {
      const data = {
        recordDateStart: queryData.error_time[0],
        recordDateEnd: queryData.error_time[1]
      }
      exportExcelErrorLianluApi(data).then((res) => {
        const file = res.data.data;
        let filename = "";
        if (queryData.error_time[0] === '') {
          const month = String(new Date().getMonth() + 1).padStart(2, '0');
          const day = String(new Date().getDate()).padStart(2, '0');
          filename = `省局总局链路监控汇总${month}-${day}`;
        } else {
          filename = `省局总局链路监控汇总${queryData.error_time[0].slice(-5, -3)}${queryData.error_time[0].slice(-2)}-${queryData.error_time[1].slice(-5, -3)}${queryData.error_time[1].slice(-2)}`;
        }
        const fileBinary = Buffer.from(file, "binary");
        const blob = new Blob([fileBinary], {
          type: "application/vnd.ms-excel",
        });
        const href = URL.createObjectURL(blob); // 创建新的URL表示指定的blob对象
        const a = document.createElement('a'); // 创建a标签
        a.style.display = 'none';
        a.href = href; // 指定下载链接
        a.download = `${filename}.xlsx`; // 指定下载文件名
        a.click(); // 触发下载
        URL.revokeObjectURL(a.href); // 释放URL对象
      });
    }
    /**
     * 格式化时间
     * @params time: string 需要转换的时间（可以被Date()转换为时间对象就可以）
     * @params format: string 需要转换成的格式 yyyy/MM/dd hh:mm:ss 
     */
    const formatTime = function (time: string, format: string, formatStr?: string) {
      const date = new Date(time);
      const year = String(date.getFullYear());
      const month = String(date.getMonth() + 1);
      const day = String(date.getDate());
      const hour = String(date.getHours());
      const minute = String(date.getMinutes());
      const second = String(date.getSeconds());
      // 查找需要转化格式中的各个字符的个数
      const yearNumber = getCharCount(format, 'y');
      const monthNumber = getCharCount(format, 'M');
      const dayNumber = getCharCount(format, 'd');
      const hourNumber = getCharCount(format, 'h');
      const minuteNumber = getCharCount(format, 'm');
      const secondNumber = getCharCount(format, 's');
      let resTimeStr = '';
      const betweenDateStr = formatStr ? formatStr : '/';
      resTimeStr += yearNumber === 0 ? '' : yearNumber === 2 ? year.slice(-2) : year;
      resTimeStr += monthNumber === 0 ? '' : monthNumber === 2 ? betweenDateStr + month.padStart(2, '0') : betweenDateStr + month;
      resTimeStr += dayNumber === 0 ? '' : dayNumber === 2 ? betweenDateStr + day.padStart(2, '0') : betweenDateStr + day;
      resTimeStr += hourNumber === 0 ? '' : hourNumber === 2 ? ' ' + hour.padStart(2, '0') : ' ' + hour;
      resTimeStr += minuteNumber === 0 ? '' : minuteNumber === 2 ? ':' + minute.padStart(2, '0') : ':' + minute;
      resTimeStr += secondNumber === 0 ? '' : secondNumber === 2 ? ':' + second.padStart(2, '0') : ':' + second;
      return resTimeStr;
    }
    // 查找一个字符串种含有某个字符的个数
    const getCharCount = function (str: string, char: string) {
      const strArr = str.split(char);
      return str.length === 0 ? 0 : strArr.length - 1;
    }
    // 重置搜索项
    const resetForm = () => {
      // const value = queryRef.value as FormInstance;
      // value.resetFields();
      queryData.error_time = ['', '']
      console.log(queryData.error_time);
    };
    onMounted(() => {
      queryErrorLianluList();
      drawerData.isShow = false;
    })
    return {
      queryRef,
      expand,
      columns,
      errorLianluList,
      tableLoading,
      queryData,
      total,
      drawerData,
      editErrorLianluData,
      errorLianluId,
      // fun
      formatTime,
      queryErrorLianluList,
      addErrorLianlu,
      editLianlu,
      delLianlu,
      exportExcel,
      closeDrawer,
      resetForm
    };
  },
});
</script>

<style scoped>
.errorLianluWarp {
  margin: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 0 8px 2px #eee;
}
</style>